package com.leo.base.exception.result;

import com.leo.base.exception.result.impl.ResultCodeEnum;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName R
 * @Description
 * @Author wangss
 * @date 2020.09.16 21:32
 * @Version 1.0
 */
@Data
public class R {

    private Boolean success;

    private Integer code;

    private String message;

    private Map<String, Object> data = new HashMap<>();

    private R() {

    }

    /**
     * 通用返回成功
     *
     * @return
     */
    public static R ok() {
        R r = new R();
        r.setSuccess(ResultCodeEnum.SUCCESS.success());
        r.setCode(ResultCodeEnum.SUCCESS.code());
        r.setMessage(ResultCodeEnum.SUCCESS.message());
        return r;
    }

    /**
     * 通用返回失败，未知错误
     *
     * @return
     */
    public static R error() {
        R r = new R();
        r.setSuccess(ResultCodeEnum.UNKNOWN_ERROR.success());
        r.setCode(ResultCodeEnum.UNKNOWN_ERROR.code());
        r.setMessage(ResultCodeEnum.UNKNOWN_ERROR.message());
        return r;
    }

    /**
     * 设置结果，形参为结果枚举
     *
     * @param result
     * @return
     */
    public static R setResult(ResultCodeEnum result) {
        R r = new R();
        r.setSuccess(result.success());
        r.setCode(result.code());
        r.setMessage(result.message());
        return r;
    }

    /**------------使用链式编程，返回类本身-----------**/

    /**
     * 自定义返回数据
     *
     * @param map
     * @return
     */
    public R data(Map<String, Object> map) {
        this.setData(map);
        return this;
    }

    /**
     * 通用设置data
     *
     * @param key
     * @param value
     * @return
     */
    public R data(String key, Object value) {
        this.data.put(key, value);
        return this;
    }

    /**
     * 自定义状态信息
     *
     * @param message
     * @return
     */
    public R message(String message) {
        this.setMessage(message);
        return this;
    }

    /**
     * 自定义状态码
     *
     * @param code
     * @return
     */
    public R code(Integer code) {
        this.setCode(code);
        return this;
    }

    /**
     * 自定义返回结果
     *
     * @param success
     * @return
     */
    public R success(Boolean success) {
        this.setSuccess(success);
        return this;
    }
}
